package system

import (
	"bytes"
	"net"
)

func BytesCombine(pBytes ...[]byte) []byte {
	length := len(pBytes)
	s := make([][]byte, length)
	for index := 0; index < length; index++ {
		s[index] = pBytes[index]
	}
	sep := []byte("")
	return bytes.Join(s, sep)
}

func ReadByte(conn net.Conn) ([]byte, error) {
	//var buf bytes.Buffer
	//io.Copy(&buf, conn)
	//buffer :=make([]byte,buf.Len())
	//_,err := buf.Read(buffer)
	//return buffer,err
	bufferLength := 512
	buffer := make([]byte, bufferLength)
	n, err := conn.Read(buffer)
	if err != nil {
		return buffer, err
	}
	buffer = buffer[0:n]
	if n == bufferLength {
		for {
			newBuffer := make([]byte, bufferLength)
			n, err = conn.Read(newBuffer)
			if err != nil {
				return buffer, err
			}
			newBuffer = newBuffer[0:n]
			buffer = BytesCombine(buffer, newBuffer)
			//fmt.Println(len(buffer))
			if n < bufferLength {
				break
			}
		}
	}
	return buffer, err
}
